// pages/word/word.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 不同年级和级别的单词书
    gradeBooks: [
      { id: 'grade1', name: '一年级单词' },
      { id: 'grade2', name: '二年级单词' },
      { id: 'grade3', name: '三年级单词' },
      { id: 'grade4', name: '四年级单词' },
      { id: 'grade5', name: '五年级单词' },
      { id: 'grade6', name: '六年级单词' },
      { id: 'cet4', name: '大学英语四级' },
      { id: 'cet6', name: '大学英语六级' }
    ],
    // 当前选择的年级
    selectedGrade: '',
    // 当前单词列表
    currentWords: [],
    // 当前单词索引
    currentIndex: 0,
    // 是否显示中文翻译
    showTranslation: false,
    // 学习进度
    progress: 0,
    // 学习状态：'select'（选择年级）, 'learning'（学习中）, 'review'（复习）
    status: 'select',
    // 是否正在加载
    loading: false,
    // 错误信息
    error: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 尝试从本地存储恢复学习状态
    this.loadStudyState();
  },

  /**
   * 从API获取单词数据
   */
  fetchWordsFromAPI(grade) {
    const that = this;
    that.setData({ loading: true, error: '' });
    
    // 根据不同的年级/级别选择不同的API端点
    let apiUrl = '';
    
    if (grade === 'cet4') {
      // 大学英语四级单词API
      apiUrl = 'https://api.example.com/words/cet4';
    } else if (grade === 'cet6') {
      // 大学英语六级单词API
      apiUrl = 'https://api.example.com/words/cet6';
    } else {
      // 小学单词API
      apiUrl = `https://api.example.com/words/grade/${grade.replace('grade', '')}`;
    }
    
    wx.request({
      url: apiUrl,
      method: 'GET',
      success(res) {
        // 假设API返回的数据格式是 { words: [{ word: '...', translation: '...', phonetic: '...' }, ...] }
        if (res.statusCode === 200 && res.data && res.data.words) {
          const shuffledWords = that.shuffleArray([...res.data.words]);
          
          that.setData({
            currentWords: shuffledWords,
            currentIndex: 0,
            showTranslation: false,
            progress: 0,
            status: 'learning',
            loading: false
          });
          
          // 保存学习状态
          that.saveStudyState();
        } else {
          that.handleAPIError('获取单词数据失败，请稍后重试');
        }
      },
      fail(error) {
        console.error('API调用失败:', error);
        // 由于这是演示环境，API可能无法访问，我们使用备用数据
        that.useFallbackWords(grade);
      },
      complete() {
        that.setData({ loading: false });
      }
    });
  },
  
  /**
   * 当API不可用时使用备用单词数据
   */
  useFallbackWords(grade) {
    // 备用单词数据，当API不可用时使用
    const fallbackWords = {
      grade1: [
        { word: 'apple', translation: '苹果', phonetic: '/ˈæpl/' },
        { word: 'book', translation: '书', phonetic: '/bʊk/' },
        { word: 'cat', translation: '猫', phonetic: '/kæt/' },
        { word: 'dog', translation: '狗', phonetic: '/dɒɡ/' },
        { word: 'egg', translation: '鸡蛋', phonetic: '/eɡ/' }
      ],
      grade2: [
        { word: 'hello', translation: '你好', phonetic: '/həˈləʊ/' },
        { word: 'world', translation: '世界', phonetic: '/wɜːld/' },
        { word: 'friend', translation: '朋友', phonetic: '/frend/' },
        { word: 'school', translation: '学校', phonetic: '/skuːl/' },
        { word: 'teacher', translation: '老师', phonetic: '/ˈtiːtʃə/' }
      ],
      grade3: [
        { word: 'computer', translation: '电脑', phonetic: '/kəmˈpjuːtə/' },
        { word: 'student', translation: '学生', phonetic: '/ˈstjuːdənt/' },
        { word: 'family', translation: '家庭', phonetic: '/ˈfæməli/' },
        { word: 'mother', translation: '妈妈', phonetic: '/ˈmʌðə/' },
        { word: 'father', translation: '爸爸', phonetic: '/ˈfɑːðə/' }
      ],
      grade4: [
        { word: 'beautiful', translation: '美丽的', phonetic: '/ˈbjuːtɪfl/' },
        { word: 'delicious', translation: '美味的', phonetic: '/dɪˈlɪʃəs/' },
        { word: 'interesting', translation: '有趣的', phonetic: '/ˈɪntrəstɪŋ/' },
        { word: 'important', translation: '重要的', phonetic: '/ɪmˈpɔːtənt/' },
        { word: 'difficult', translation: '困难的', phonetic: '/ˈdɪfɪkəlt/' }
      ],
      grade5: [
        { word: 'information', translation: '信息', phonetic: '/ˌɪnfəˈmeɪʃn/' },
        { word: 'technology', translation: '技术', phonetic: '/tekˈnɒlədʒi/' },
        { word: 'environment', translation: '环境', phonetic: '/ɪnˈvaɪrənmənt/' },
        { word: 'education', translation: '教育', phonetic: '/ˌedʒuˈkeɪʃn/' },
        { word: 'development', translation: '发展', phonetic: '/dɪˈveləpmənt/' }
      ],
      grade6: [
        { word: 'opportunity', translation: '机会', phonetic: '/ˌɒpəˈtjuːnəti/' },
        { word: 'responsibility', translation: '责任', phonetic: '/rɪˌspɒnsəˈbɪləti/' },
        { word: 'communication', translation: '交流', phonetic: '/kəˌmjuːnɪˈkeɪʃn/' },
        { word: 'determination', translation: '决心', phonetic: '/dɪˌtɜːmɪˈneɪʃn/' },
        { word: 'achievement', translation: '成就', phonetic: '/əˈtʃiːvmənt/' }
      ],
      cet4: [
        { word: 'abandon', translation: '放弃', phonetic: '/əˈbændən/' },
        { word: 'ability', translation: '能力', phonetic: '/əˈbɪləti/' },
        { word: 'abroad', translation: '国外', phonetic: '/əˈbrɔːd/' },
        { word: 'absolute', translation: '绝对的', phonetic: '/ˈæbsəluːt/' },
        { word: 'academic', translation: '学术的', phonetic: '/ˌækəˈdemɪk/' },
        { word: 'accept', translation: '接受', phonetic: '/əkˈsept/' },
        { word: 'access', translation: '通道，接近', phonetic: '/ˈækses/' },
        { word: 'according', translation: '根据', phonetic: '/əˈkɔːdɪŋ/' },
        { word: 'account', translation: '账户，解释', phonetic: '/əˈkaʊnt/' },
        { word: 'achieve', translation: '实现', phonetic: '/əˈtʃiːv/' }
      ],
      cet6: [
        { word: 'abandon', translation: '放弃', phonetic: '/əˈbændən/' },
        { word: 'ability', translation: '能力', phonetic: '/əˈbɪləti/' },
        { word: 'abnormal', translation: '异常的', phonetic: '/æbˈnɔːml/' },
        { word: 'abolish', translation: '废除', phonetic: '/əˈbɒlɪʃ/' },
        { word: 'abound', translation: '丰富', phonetic: '/əˈbaʊnd/' },
        { word: 'abroad', translation: '国外', phonetic: '/əˈbrɔːd/' },
        { word: 'absolute', translation: '绝对的', phonetic: '/ˈæbsəluːt/' },
        { word: 'absorb', translation: '吸收', phonetic: '/əbˈsɔːb/' },
        { word: 'abstract', translation: '抽象的', phonetic: '/ˈæbstrækt/' },
        { word: 'abundant', translation: '丰富的', phonetic: '/əˈbʌndənt/' }
      ]
    };
    
    const words = fallbackWords[grade] || [];
    const shuffledWords = this.shuffleArray([...words]);
    
    this.setData({
      currentWords: shuffledWords,
      currentIndex: 0,
      showTranslation: false,
      progress: 0,
      status: 'learning',
      loading: false,
      error: '当前使用离线单词数据'
    });
    
    // 保存学习状态
    this.saveStudyState();
  },
  
  /**
   * 处理API错误
   */
  handleAPIError(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
    
    this.setData({
      error: message,
      loading: false,
      status: 'select'
    });
  },
  
  /**
   * 选择年级
   */
  selectGrade(e) {
    const grade = e.currentTarget.dataset.grade;
    this.setData({ selectedGrade: grade });
    
    // 从API获取单词数据
    this.fetchWordsFromAPI(grade);
  },

  /**
   * 显示/隐藏翻译
   */
  toggleTranslation() {
    this.setData({
      showTranslation: !this.data.showTranslation
    });
  },

  /**
   * 下一个单词
   */
  nextWord() {
    const { currentWords, currentIndex } = this.data;
    
    if (currentIndex < currentWords.length - 1) {
      const nextIndex = currentIndex + 1;
      const newProgress = Math.round((nextIndex / currentWords.length) * 100);
      
      this.setData({
        currentIndex: nextIndex,
        showTranslation: false,
        progress: newProgress
      });
    } else {
      // 学习完成
      wx.showToast({
        title: '恭喜你完成了学习！',
        icon: 'success'
      });
      
      this.setData({
        status: 'review'
      });
    }
    
    // 保存学习状态
    this.saveStudyState();
  },

  /**
   * 上一个单词
   */
  prevWord() {
    const { currentWords, currentIndex } = this.data;
    
    if (currentIndex > 0) {
      const prevIndex = currentIndex - 1;
      const newProgress = Math.round((prevIndex / currentWords.length) * 100);
      
      this.setData({
        currentIndex: prevIndex,
        showTranslation: false,
        progress: newProgress
      });
      
      // 保存学习状态
      this.saveStudyState();
    }
  },

  /**
   * 重新学习
   */
  restartLearning() {
    const { selectedGrade } = this.data;
    
    // 重新从API获取单词数据
    this.fetchWordsFromAPI(selectedGrade);
  },

  /**
   * 返回选择年级
   */
  backToSelect() {
    this.setData({
      status: 'select'
    });
  },

  /**
   * 打乱数组顺序（Fisher-Yates 洗牌算法）
   */
  shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  },

  /**
   * 保存学习状态到本地存储
   */
  saveStudyState() {
    const { selectedGrade, currentIndex, currentWords, status } = this.data;
    
    const studyState = {
      selectedGrade,
      currentIndex,
      status,
      timestamp: Date.now()
    };
    
    wx.setStorageSync('wordStudyState', studyState);
  },

  /**
   * 从本地存储加载学习状态
   */
  loadStudyState() {
    const studyState = wx.getStorageSync('wordStudyState');
    
    if (studyState && studyState.timestamp) {
      // 检查状态是否在24小时内有效
      const now = Date.now();
      const diff = now - studyState.timestamp;
      const hoursPassed = diff / (1000 * 60 * 60);
      
      if (hoursPassed < 24) {
        const words = this.data.wordData[studyState.selectedGrade] || [];
        
        this.setData({
          selectedGrade: studyState.selectedGrade,
          currentWords: words,
          currentIndex: studyState.currentIndex,
          status: studyState.status,
          progress: Math.round((studyState.currentIndex / words.length) * 100)
        });
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // 页面隐藏时保存学习状态
    this.saveStudyState();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 页面卸载时保存学习状态
    this.saveStudyState();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '单词学习助手',
      path: '/pages/word/word'
    };
  }
})